import dayjs from 'dayjs';

export function json(value) {
  return JSON.stringify(value);
}

export function formatDate(value, pattern = 'YYYY-MM-DD HH:mm:ss') {
  return value ? dayjs(value)
    .format(pattern) : null;
}

export function asDate(value) {
  return formatDate(value, 'YYYY-MM-DD');
}

export function currentDate(value) {
  const date = value ? dayjs(value) : dayjs();
  return date.format('YYYY-MM-DD');
}

export function ellipse(value, length = 10) {
  return value && value.length > length ? `${value.substring(0, length - 1)}...` : value;
}

export function relativeTime(time) {
  const date = dayjs(time);
  const timestamp = date.unix();
  let interval = Math.round(new Date() / 1000) - timestamp;
  const postfix = interval > 0 ? '前' : '后';
  interval = Math.abs(interval);
  if (interval < 86400) {
    const strArr = ['小时', '分钟', '秒'];
    const secondArr = [3600, 60, 1];

    const { length } = strArr;
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < length; i++) {
      const res = Math.floor(interval / secondArr[i]);
      if (res !== 0) {
        return res + strArr[i] + postfix;
      }
    }
  }
  return date.format('YYYY-MM-DD');
}
